//
//  GoalSettingModel.swift
//  MYModule
//
//  Created by 尹琼 on 2022/11/10.
//

import UIKit
import SQLite
import HandyJSON
import SwiftDate
import MYModule

/// 目标设置存储
/// 一份默认的，1份有周天的
/// 所以表中总共只有2份数据

open class ExerciseGoalsModel: NSObject, MYSQLiteTableiabe, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    /// 1 是默认的  0 是带周天数设置的
    public var isNormal: Int = 1
    
    /// 默认的锻炼目标这里永远为空
    public var weekDays: [Int] = []
    
    /// 开关（默认的总是开,  normal 那份无效）
    public var open: Int = 1
    
    /// 步数
    public var step: Int = 8000
    
    /// 卡路里
    public var kcal: Int = 300
    
    /// 距离
    public var distance: Int = 0
    
    /// 锻炼时长
    public var exerciseTime: Int = 30
    
    /// 是否同步了戒指 = 1 同步， = 0 未同步
    public var syncRecord: Int = 0
    
    open var isEmpty: Bool {
        
        return id == 0
    }
    
    public var stringValueExpressibleSetters: [Setter]? {
        let expression_weekDays = Expression<[Int]>("weekDays")
        return [
            expression_weekDays <- weekDays
            
        ]
    }
    
    required public override init() {}
    
    public static func model(isNormal: Bool) ->ExerciseGoalsModel {
        
        let id: Int64 = isNormal ? 1 : 2
        
        let query = table.filter(expression_id == id)
        guard let row = try? db.pluck(query), let model = ExerciseGoalsModel.deserialize(from: row) else {
            
            let model = ExerciseGoalsModel()
            model.isNormal = isNormal == true ? 1 : 0
            
            return model
        }
        
        return model
    }
    
    
    public func updateData() {
        
        if isNormal == 1 {
            weekDays.removeAll()
        }
        
        let query = table.filter(expression_id == id)
        guard let _ = try? db.pluck(query) else {
            self.insert()
            return
        }
        self.update()
        
    }
    
    
    public static func currentGoal(weekDay: Int) ->ExerciseGoalsModel {
        
        
        let weeksModel = self.model(isNormal: false)
        if weeksModel.open == 1 && weeksModel.weekDays.contains(weekDay) {
            return weeksModel
        }
        return self.model(isNormal: true)
        
    }
    
    
    /// 判断一天是否是锻炼日
    /// - Parameter date: 日期
    /// - Returns: bool
    public func isTrainingDay(date: Date) ->Bool {
        
        if weekDays.isEmpty || isNormal == 0 {
            return false
        }
        return weekDays.contains(date.weekday)
        
    }
    
    
    
    
}
